using System;
using System.Collections.Generic;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using Newtonsoft.Json.Linq;

namespace AvaloniaApplication1.Services;

public class MessageParser: IMessageParser
{
    /// <summary>
    /// 解析MQTT消息
    /// </summary>
    /// <param name="deviceId">设备名称</param>
    /// <param name="topic">主题</param>
    /// <param name="payload">原始消息内容</param>
    /// <returns>返回MqttMessageModel对象</returns>
    public MqttMessageDataModel ParseMessage(string deviceId, string topic, string payload)
    {
      var messageData = new MqttMessageDataModel(deviceId, topic, payload);
            
            try
            {
                var json = JObject.Parse(payload);
                
                // 根据主题类型处理不同的数据格式
                if (topic.Contains("modbus"))
                {
                    messageData.MessageType = "Modbus";
                    ParseModbusData(json, messageData.ParsedData);
                }
            
                else
                {
                    messageData.MessageType = "Generic";
                    // 通用处理 当前具体处理方式为：遍历JSON对象并添加到字典中
                    foreach (var property in json.Properties())
                    {
                        messageData.ParsedData[property.Name] = property.Value.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                messageData.MessageType = "Error";
                messageData.ParsedData["Error"] = ex.Message;
            }
            
            return messageData;
        }
        
        private void ParseModbusData(JObject json, Dictionary<string, object> parsedData)
        {
            // 处理Modbus特定数据
            if (json.ContainsKey("register_0"))
                parsedData["Temperature"] = json["register_0"]?.ToString();
                
            if (json.ContainsKey("register_1"))
                parsedData["Humidity"] = json["register_1"]?.ToString();
                
            if (json.ContainsKey("register_10"))
                parsedData["DeviceId"] = json["register_10"]?.ToString();
                
            if (json.ContainsKey("register_11"))
                parsedData["BaudRate"] = json["register_11"]?.ToString();
        }
        
}